<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace weapp\PointsShop\logic;

use think\Db;

/**
 * 积分商城业务逻辑
 */
class PointsShopLogic
{

    // 系统商品操作时，积分商品的被动处理
    public function pointsGoodsPassiveHandle($aid = [])
    {
        if (!empty($aid)) {
            $where = [
                'aid' => ['IN', $aid]
            ];
            $update = [
                'goods_status' => 2,
                'goods_passive' => 2,
                'update_time' => getTime(),
            ];
            Db::name('weapp_points_goods')->where($where)->update($update);
        }
    }

    // 系统订单列表数据，积分商城订单数据处理
    public function pointsShopOrderDataHandle($list = [], &$OrderData = [], &$DetailsData = [])
    {
        foreach ($list as $key_0 => $value_0) {
            // 如果是积分商城订单并且有顶订单商品详情则执行
            if (!empty($value_0['points_shop_order']) && !empty($value_0['Details'])) {
                foreach ($value_0['Details'] as $key_1 => $value_1) {
                    $field = !empty($value_1['pointsGoodsBuyField']) ? $value_1['pointsGoodsBuyField'] : [];
                    if (!empty($field)) {
                        // 订单商品单价数据处理
                        $value_1['product_price'] = !empty($field['goods_points']) ? intval($field['goods_points']) . '<span class="unit">积分</span>' : $value_1['product_price'];
                        // if (!empty($field['goods_price'])) $value_1['product_price'] .= '+' . unifyPriceHandle($field['goods_price']) . '元';
                        if (!empty($field['goods_price'])) $value_1['product_price'] .= '+<span class="unit">￥</span>' . unifyPriceHandle($field['goods_price']);
                        // 订单商品小计数据处理
                        $value_1['subtotal'] = !empty($field['goodsSinglePoints']) ? intval($field['goodsSinglePoints']) . '<span class="unit">积分</span>' : $value_1['subtotal'];
                        // if (!empty($field['goodsSinglePrice'])) $value_1['subtotal'] .= '+' . unifyPriceHandle($field['goodsSinglePrice']) . '元';
                        if (!empty($field['goodsSinglePrice'])) $value_1['subtotal'] .= '+<span class="unit">￥</span>' . unifyPriceHandle($field['goodsSinglePrice']);
                        // 订单商品总价数据处理
                        $value_0['order_total_amount'] = !empty($value_1['subtotal']) ? $value_1['subtotal'] : $value_0['order_total_amount'];
                        // 订单商品应付款数据处理
                        $value_0['order_amount'] = !empty($field['goodsTotalPoints']) ? intval($field['goodsTotalPoints']) . '<span class="unit">积分</span>' : $value_0['order_amount'];
                        // if (!empty($field['goodsTotalPrice'])) $value_0['order_amount'] .= '+' . unifyPriceHandle($field['goodsTotalPrice']) . '元';
                        if (!empty($field['goodsTotalPrice'])) $value_0['order_amount'] .= '+<span class="unit">￥</span>' . unifyPriceHandle($field['goodsTotalPrice']);
                        // 支付方式处理，如没有产生真实金额支付则变更为无需支付类型(noNeedPay)
                        if (empty($field['goodsTotalPrice'])) $value_0['pay_name'] = 'noNeedPay';
                    }
                    $value_0['Details'][$key_1] = $value_1;
                    $DetailsData[$key_1] = !empty($DetailsData[$key_1]) ? $value_0['Details'][$key_1] : [];
                }
            }

            $list[$key_0] = $value_0;
            $OrderData = !empty($OrderData) ? $list[$key_0] : [];
        }

        return $list;
    }

    // 添加订单表字段处理
    public function addShopOrderTableHandle($prefix = '')
    {
        if (!empty($prefix)) {
            // 订单表字段
            $shopOrderTableField = Db::query("SHOW COLUMNS FROM {$prefix}shop_order");
            $shopOrderTableField = get_arr_column($shopOrderTableField, 'Field');

            // 是否积分订单(0:普通订单; 1:积分订单;)
            if (!empty($shopOrderTableField) && !in_array('points_shop_order', $shopOrderTableField)) {
                $sql = "ALTER TABLE `{$prefix}shop_order` ADD COLUMN `points_shop_order` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '是否积分订单(0:普通订单; 1:积分订单;)' AFTER `logistics_type`";
                @Db::execute($sql);
            }

            schemaTable('shop_order');
        }
    }

    // 删除订单表字段处理
    public function delShopOrderTableHandle($prefix = '')
    {
        if (!empty($prefix)) {
            // 订单表字段
            $shopOrderTableField = Db::query("SHOW COLUMNS FROM {$prefix}shop_order");
            $shopOrderTableField = get_arr_column($shopOrderTableField, 'Field');

            // 核销记录表ID(weapp_verify表)
            if (!empty($shopOrderTableField) && in_array('points_shop_order', $shopOrderTableField)) {
                $sql = "ALTER TABLE `{$prefix}shop_order` DROP COLUMN `points_shop_order`";
                @Db::execute($sql);
            }

            schemaTable('shop_order');
        }
    }

    // 获取商品规格组合Html
    public function getGoodsSpecCombi($goodsSpec = [], $aid = 0, $goods_id = 0)
    {
        if (empty($goodsSpec) || empty($aid)) return "";

        // 规格数量统计
        $goodsSpecCount = [];
        foreach ($goodsSpec as $key => $value) {
            $goodsSpecCount[$key] = count($value);
        }

        // 规格数组排序
        asort($goodsSpecCount);
        $goodsSpecCombi = [];
        foreach ($goodsSpecCount as $key => $value) {
            $goodsSpecCombi[$key] = $goodsSpec[$key];
        }

        // 提取规格数组key键
        $goodsSpecKeys = array_keys($goodsSpecCombi);

        // 数据组合
        $goodsSpecCombi = $this->getGoodsSpecMultipleCombi($goodsSpecCombi);
        // dump($goodsSpecCombi);exit;
        // 查询规格信息
        $where = [
            'aid' => $aid,
            'spec_is_select' => 1,
        ];
        // 查询规格名称
        $order = 'spec_mark_id asc, spec_value_id asc';
        $goodsSpecName = Db::name('product_spec_data')->where($where)->order($order)->group('spec_mark_id')->getField('spec_mark_id, spec_name');
        // 查询规格值
        $order = 'spec_value_id desc';
        $goodsSpecValue = Db::name('product_spec_data')->where($where)->order($order)->getField('spec_value_id, spec_value, spec_mark_id');

        // 查询规格价格
        $where = [
            'aid' => $aid,
        ];
        $field = 'spec_value_id, spec_price, spec_stock, spec_sales_num';
        $goodsSpecPrice = Db::name('product_spec_value')->where($where)->order('spec_price asc')->getField($field);

        // 查询积分商品规格价格
        $where = [
            'aid' => $aid,
            'goods_id' => $goods_id,
        ];
        $field = 'spec_keys, aid, spec_id, goods_id, spec_join, spec_stock, spec_price, spec_points';
        $pointsGoodsSpec = Db::name('weapp_points_goods_spec')->where($where)->order('spec_price asc')->getField($field);

        // 组合HTML
        $returnHtml  = "<table class='table table-bordered' id='goodsSpecTable' border='1' cellpadding='10' cellspacing='10'><thead><tr style='background-color: #f7f7f7;'>";

        // 显示第一行的数据
        foreach ($goodsSpecKeys as $value) {
            $returnHtml .= "<td><b><span class=''>{$goodsSpecName[$value]}</span></b></td>";
        }
        $returnHtml .= "<td><b>售卖价</b></td>";
        $returnHtml .= "<td><b>总库存</b></td>";
        // $returnHtml .= "<td><b>是否参与</b></td>";
        $returnHtml .= "<td><b>积分设置</b></td>";
        $returnHtml .= "<td><b>库存设置</b></td>";
        $returnHtml .= "</tr></thead><tbody>";

       // 显示第二行开始
       foreach ($goodsSpecCombi as $key => $value_1) {
            $returnHtml .= "<tr>";
            $specKeysName = [];
            foreach ($value_1 as $value_2) {
                $returnHtml .= "<td><span>{$goodsSpecValue[$value_2]['spec_value']}</span></td>";
                $specKeysName[$value_2] = $goodsSpecName[$goodsSpecValue[$value_2]['spec_mark_id']].':'.$goodsSpecValue[$value_2]['spec_value'];
            }

            ksort($specKeysName);
            $pointsSpecKeys = implode('_', array_keys($specKeysName));

            $returnHtml .= "<input type='hidden' name='goodsSpecSet[pointsSpecKeys][]' value='{$pointsSpecKeys}'>";
            $returnHtml .= "<td><strong>￥{$goodsSpecPrice[$pointsSpecKeys]['spec_price']}</strong></td>";
            $returnHtml .= "<td>{$goodsSpecPrice[$pointsSpecKeys]['spec_stock']}</td>";
            // 积分商品规格ID
            $returnHtml .= "<input type='hidden' name='goodsSpecSet[$pointsSpecKeys][specID]' value='{$pointsGoodsSpec[$pointsSpecKeys]['spec_id']}'>";
            // 是否参与
            $returnHtml .= "<input type='hidden' name='goodsSpecSet[$pointsSpecKeys][specJoin]' value='1'>";
            // $specJoin = '';
            // if (!empty($pointsGoodsSpec[$pointsSpecKeys]['spec_join'])) $specJoin = "checked='true'";
            // $returnHtml .= "<td><label><input class='specJoin' type='checkbox' name='goodsSpecSet[$pointsSpecKeys][specJoin]' value='1' {$specJoin}> 参与</label></td>";
            // 积分设置
            $returnHtml .= "<td class='w340'>";
            $returnHtml .= "<input type='text' class='input-txt w95 pr35 specPoints' name='goodsSpecSet[$pointsSpecKeys][specPoints]' placeholder='0' value='{$pointsGoodsSpec[$pointsSpecKeys]['spec_points']}'><span class='cw-cell-unit'>积分</span>";
            $returnHtml .= "<span style='margin: 0 5px;'>+</span>";
            $returnHtml .= "<input type='text' class='input-txt w95 pr35 specPrice' name='goodsSpecSet[$pointsSpecKeys][specPrice]' placeholder='0' value='{$pointsGoodsSpec[$pointsSpecKeys]['spec_price']}'><span class='cw-cell-unit'>元</span>";
            $returnHtml .= "</td>";
            // 库存设置
            $returnHtml .= "<td><input type='text' class='input-txt w95 pr35 specStock' name='goodsSpecSet[$pointsSpecKeys][specStock]' placeholder='0' value='{$pointsGoodsSpec[$pointsSpecKeys]['spec_stock']}'><span class='cw-cell-unit'>件</span></td>";
            $returnHtml .= "</tr>";
        }
        $returnHtml .= "</tbody>";
        $returnHtml .= "</table>";

        return $returnHtml;
    }

    // 获取商品规格多种组合排序
    private function getGoodsSpecMultipleCombi()
    {
        $goodsSpec = func_get_args();
        $goodsSpec = current($goodsSpec);
        $goodsSpec_1 = array_shift($goodsSpec);
        $result = [];
        foreach ($goodsSpec_1 as $key => $value) {
            $result[] = array($value);
        }
        foreach ($goodsSpec as $key => $value) {                                
            $result = $this->getGoodsSpecMultipleCombiArray($result, $value);
        }
        return $result;
    }

    // 获取商品规格多种组合排序数组
    private function getGoodsSpecMultipleCombiArray($goodsSpec_1, $goodsSpec_2)
    {
        $result = [];
        foreach ($goodsSpec_1 as $value_1) {
            foreach ($goodsSpec_2 as $value_2) {
                $value = $value_1;
                $value[] = $value_2;
                $result[] = $value;
            }
        }
        return $result;
    }
}